#include <bits/stdc++.h>
using namespace std;

class Solution {
    int dx[4] = {0, 0, -1, 1};
    int dy[4] = {-1, 1, 0, 0};
    int m, n;

public:
    vector<vector<int>> pacificAtlantic(vector<vector<int>>& h) {
        m = h.size(), n = h[0].size();
        vector<vector<bool>> pac(m, vector<bool>(n));
        vector<vector<bool>> atl(m, vector<bool>(n));
        vector<vector<int>> res;

        for (int i = 0; i < m; i++)
            dfs(h, i, 0, pac);
        for (int j = 0; j < n; j++)
            dfs(h, 0, j, pac);

        for (int i = 0; i < m; i++)
            dfs(h, i, n - 1, atl);
        for (int j = 0; j < n; j++)
            dfs(h, m - 1, j, atl);

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (pac[i][j] && atl[i][j]) {
                    res.push_back({i, j});
                }
            }
        }
        return res;
    }

    void dfs(vector<vector<int>>& h, int i, int j, vector<vector<bool>>& vis) {
        vis[i][j] = true;
        for (int k = 0; k < 4; k++) {
            int x = dx[k] + i;
            int y = dy[k] + j;
            if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && h[i][j] <= h[x][y]) {
                dfs(h, x, y, vis);
            }
        }
    }
};